import pandas as pd
import yaml

from yaml import SafeLoader
from datareport.api import ImageUtil
from datareport.api.DataSource import DataSource
from datareport.api.annotation.Font import Font
from datareport.impl.paragraph.base.BaseParagraph import BaseParagraph
from datareport.api.annotation.Style import style


@style()
class KaiZhanQingKuang_pingci_jiceng_41(BaseParagraph):
    """
    组织生活开展频次-基层党支部情况
    """

    def __init__(self):
        super().__init__()
        self.text = '''3 、 从 基 层 党 支 部 来 看 ： \
{} ，年 度 开 展 组 织 生 活 场 次 为{}场 次 ， 平 均 每 月 超 过{}场 次 。 \
'''
        self.sort = 31
        self.section = 10

    def plot(self, df, plt):
        pass

    def getData(self, result):
        pass

    def start(self, conn, year, plt):
        self.text = self.text.replace(' ', '').replace('\n', '')
        df = pd.read_sql('''select partyOrgName,partyBranchName,count(1) num from(
        select partyOrgName,partyBranchName from t_meetingplan where year(createTime)={} 
        and activityId in (select activityId from t_meetingrecord)
        )new group by partyOrgName,partyBranchName
        '''.format(year), con=conn)
        partyBranchNames = '、'.join(df[df['num'] == df['num'].max()]['partyBranchName'].values.tolist())
        ## 二级下最大和最小基层情况
        def find_branch_names(x):
            max_val = x['num'].max()
            min_val = x['num'].min()
            max_idx = x[x['num'] == max_val].index[0]
            min_idx = x[x['num'] == min_val].index[0]
            max_name = x.loc[max_idx, 'partyBranchName']
            min_name = x.loc[min_idx, 'partyBranchName']
            return pd.Series([max_name, min_name, max_val, min_val],
                             index=['max_partyBranchName', 'min_partyBranchName', '最大', '最小'])

        max_min_df = df.groupby('partyOrgName').apply(find_branch_names)
        temp = max_min_df.reset_index()
        temp.rename(columns={"max":"最高","min":"最低"},inplace=True)
        self.image = ImageUtil.plot(temp, ylable='最高最低基层频次',legend_switch=True,size=(6,2.5))
        # max_min_df['diff'] = max_min_df['max'] - max_min_df['min']

        self.text = self.text.replace(' ', '').format(partyBranchNames, df['num'].max(), round(df['num'].max() / 12))
        self.fonts.append(Font(text=self.text))


if __name__ == '__main__':
    with open('D:\work\sanhuiyike\datareport\config.yaml', encoding='utf-8') as f:
        data = yaml.load(f, Loader=SafeLoader)
    con = DataSource(data['datasource']).conn
    KaiZhanQingKuang_pingci_jiceng_41().start(con, 2023, '')
